

#include "user_inc.h"


static center_information* cebter_head = 0;
static uint16_t cnb[THEME_END];

void center_init(void)
{
    memset(cnb,0,sizeof(cnb));
    cebter_head = 0;
}

int8_t center_subscription(center_theme id,theme_Callback cb,center_information* hd)
{
    center_information* tg = cebter_head;
    if (hd == 0)
    {
        return -1;
    }
    
    if (id >= THEME_END)
    {
        return -2;
    }   
    
    
    for (;tg != 0;tg = tg->next)
    {
        //已经注册过，
        if (tg == hd)
        {
            
            if (tg->cb != 0)
            {
                cnb[tg->id]--;
            }            
            
            
            tg->cb = cb;
            tg->id = id;

            cnb[tg->id]++;
            return 0;
        }        
    }
    
    if (cb != 0)
    {
        cnb[id]++;
    }    
    
    hd->cb = cb;
    hd->id = id;
    hd->next = cebter_head;
    cebter_head = hd;

    return 0;

}

int8_t center_release(center_theme id,void *data,unsigned int size)
{
    center_information* tg = cebter_head;
    int8_t ack=0;
    

    if (id >= THEME_END)
    {
        return -1;
    }

    if ((data == 0) || (size == 0))
    {
        return -2;
    }

    //没人订阅这个消息，直接返回
    if (cnb[id] == 0)
    {
        return 0;
    }
    
    
    

    for (; tg != 0; tg = tg->next)
    {
       if ((tg->id == id) && (tg->cb != 0))
       {
           ack = tg->cb(data,size);

            //返回0 表示不再订阅
           if (ack == 0)
           {               
               cnb[id]--;
               tg->cb =0;
               
           }
           
       }       
    }   


    return 0;
}


